package com.longmao.edumsm.controller;

import com.longmao.commonutils.R;
import com.longmao.edumsm.service.MsmService;
import com.longmao.edumsm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author longmao
 * @date 2022/2/21 10:08
 * Content:
 */
@RestController
//@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送短信的方法
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //从redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) return R.ok();
        //获取不到，生成随机的值，传递给腾讯云发送
        code = RandomUtil.getFourBitRandom();
        boolean isSend = msmService.send(code, phone);
        if(isSend) {
            //发送成功，把发送得验证码存储到redis中，设置有效时间（key, value, 时间值, 单位）
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }
}
